package com.wuyong.chapter4;

import com.wuyong.Chapter3.Queue;

/**
 * 链表实现队列
 * @param <E>
 */
public class LinkedListQueue<E> implements Queue<E> {

    private class Node {
        private E e;
        private Node next;

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        public Node(E e) {
            this.e = e;
            this.next = null;
        }

        public Node() {
            this.e = null;
            this.next = null;
        }

        @Override
        public String toString() {
            if (e != null) {
                return e.toString();
            }
            return "";
        }
    }

    private Node head, tail;
    private int size;

    public LinkedListQueue() {
        head = null;
        tail = null;
        size = 0;
    }


    @Override
    public void enqueue(E e) {
        if (tail == null) {
            tail = new Node(e);
            head = tail;
        } else {
            Node node = new Node(e);
            tail.next = node;
            tail = node;
        }
        size ++;
    }

    @Override
    public E dequeue() {
        if (size <= 0) {
            throw  new IllegalArgumentException("Queue is empty");
        }
        Node retNode = head;

        head = retNode.next;
        retNode.next = null;
        if (head == null){
            tail = null;
        }
        size --;
        return retNode.e;
    }

    @Override
    public E getFront() {
        if (size <= 0) {
            throw  new IllegalArgumentException("Queue is empty");
        }
        return head.e;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }
}
